package com.vhall.component.service.goods.listener;

import com.alibaba.fastjson.JSONObject;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.plugin.common.constant.RoomConstant;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.plugin.core.service.event.PaasMessageReqDTO;
import com.vhall.component.service.goods.common.GoodsConstant;
import com.vhall.component.service.goods.event.LiveGoodsListRefreshEvent;
import com.vhall.component.service.room.RoomInnerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 直播间商品列表刷新事件监听
 *
 * @author yuanzh
 * @date 2021/10/29
 */
@Service
@Slf4j
@EnableAsync
public class LiveGoodsListRefreshEventListener implements ApplicationListener<LiveGoodsListRefreshEvent> {

    @Autowired
    private PaasService paasService;

    @Autowired
    private RoomInnerService roomInnerService;

    /**
     * 直播间商品列表刷新事件处理
     *
     * @param event 事件对象
     */
    @Async
    @Override
    public void onApplicationEvent(LiveGoodsListRefreshEvent event) {
        Set<Integer> ilIds = new HashSet<>(event.getIlIds());
        String eventMessage = event.getEventMessage();
        try {
            for (Integer ilId : ilIds) {
                RoomsEntityDTO roomInfo = roomInnerService.getRoomInfoByIlId(String.valueOf(ilId));
                if (Objects.isNull(roomInfo) || roomInfo.getStatus() != RoomConstant.STATUS_START) {
                    log.info("【直播间商品列表刷新事件】房间不存在或者未开播，无需处理，ilId={}", ilId);
                    continue;
                }
                JSONObject messageBody = new JSONObject();
                messageBody.put("type", GoodsConstant.GOODS_LIST_REFRESH_MESSAGE_TYPE);
                messageBody.put("event", eventMessage);
                PaasMessageReqDTO paasMessageReq = new PaasMessageReqDTO.Builder(roomInfo.getChannelId(), messageBody.toString())
                        .initDefault().build();
                paasMessageReq.setType("service_custom");
                paasService.sendMessage(paasMessageReq);
            }
        } finally {
            log.info("【直播间商品列表刷新事件】消息事件处理完成，ilIds={}，eventMessage={}", ilIds, eventMessage);
        }
    }
}
